﻿using Microsoft.AspNetCore.Identity;
using My.Admin.Dto.User;
using My.Admin.Model;
using My.Admin.Model.System;
using My.Admin.Repository;
using My.Admin.Service.System.IService;
using My.Core.SqlSugar.model;
using System.ComponentModel;

namespace My.Admin.Service.System
{
	public class SysUserService : BaseService<SysUser>, ISysUserService
	{
		private readonly ISysOrgService _sysOrgService;
		private readonly UserManager _userManager;

		public SysUserService(ISysOrgService sysOrgService, UserManager userManager)
		{
			_sysOrgService = sysOrgService;
			_userManager = userManager;
		}

		/// <summary>
		/// 获取用户分页列表
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		public async Task<PagedInfo<SysUser>> Page(PageUserInput input)
		{
			// 获取用户拥有的机构集合
			var userOrgIdList = await _sysOrgService.GetUserOrgIdList();
			List<long> orgList = null;
			// 各管理员只能看到自己机构下的用户列表
			orgList = _userManager.SuperAdmin ? null : userOrgIdList;

			int totalCount = 0;
			var lSysUser = Queryable();

			if (lSysUser == null)
			{
				input.TotalNum = 0;
				return null;
			}
			input.TotalNum = totalCount;

			lSysUser = lSysUser
				.WhereIF(orgList != null, u => orgList.Contains(u.OrgId))
				.Where(x => x.RealName.Contains(input.RealName));

			return await lSysUser.ToPageAsync(input);
		}
	}
}
